// pages/home/home.js
import * as API_Stroe from '../../api/store'
import * as API_Order from '../../api/order'
import * as socketUtil from'../../api/socketUtil'
import * as API_Adamember from '../../api/adaMember'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //店铺
    store:{},
    totalPrice:0,
    totalSales:0,
    visitNum:0,
    scanreturn:false,
    storeList:[],
    showStoreManager:false,
    showYanQuan:false,
    jishi:false,
    array: ['核销', '售后'],
    smindex: 0,
    shumaindex: 0,
    menuClientRect: {}
  },
  toDoor:function() {
    wx.navigateTo({
      url: '/pages/doortodoor/doortodoor',
    })
  },
  bindPickerChange: function(e) {
    this.setData({
      smindex: e.detail.value
    })
    this.scanCode()
  },
  bindShumaPickerChange: function(e) {
    // console.log(e)
    if(e.currentTarget.dataset.type == 1) {
      this.setData({
        shumaindex: e.detail.value
      })
      this.codeHandle()
    } else if(e.currentTarget.dataset.type == 2) {
      const type = e.detail.value == 0 ? 1 : 2
      wx.navigateTo({
        url: '/pages/verificationRecord/verificationRecord?type='+type,
      })
    }

  },
  toFitment(){
    wx.navigateTo({
      url: '../fitment/fitment',
    })
  },
  RECEIVE_MSG_INFORM:function(json){
    //收到新消息
    let reqParam={storeId:this.data.store.id} ;
    socketUtil.sendData("MY_MSG_UNREAD_COUNT",reqParam);
  },
  MY_MSG_UNREAD_COUNT:function(json){
   let unreadMsgCount= json.info.unreadMsgCount;
   if(unreadMsgCount==0){
    wx.removeTabBarBadge({
      index: 1
     })
   }else{
    wx.setTabBarBadge({
      index: 1,
      text: unreadMsgCount+''
     })
   }
 },
 codeHandle(){
  wx.navigateTo({
    url: '/pages/verificationHandle/verificationHandle?index='+this.data.shumaindex,
  })
 },
 toSelectStore(){
  wx.navigateTo({
    url: '/pages/selectStore/selectStore',
  })
 },
 getMethod() {
    let method = ''
    if(this.data.smindex == 0) {
      method = 'scanVerify'
    } else if(this.data.smindex == 1) {
      method = 'scanAfter'
    }
    return method
 },
 scanCode(){
   const that = this
   this.setData({scanreturn:true})
   wx.scanCode({
     onlyFromCamera: false,
     scanType:['barCode','datamatrix','pdf417','qrCode'],
     success(res){
         console.log(res.result)
       var verifyCode = res.result
       let params = {
        verifyCode:verifyCode
       }
      //  let type = that.data.smindex == 0 ? 1 : 2
       const method = that.getMethod()
       API_Order[method](params).then(res=>{
           console.log(res)
         if(res.code == 200){
           wx.showToast({
             title: '核销成功',
           })
           setTimeout(()=>{
            // let loginType = wx.getStorageSync('loginType')
            // let type = loginType === 1 ? 2 : 1
            let type = that.data.smindex == 0 ? 1 : 2
            console.log(type)
            wx.navigateTo({
              url: '/pages/verificationRecord/verificationRecord?type=' + type,
            })
        }, 1500)
         }else{
             console.log('else')
           setTimeout(function() {
            wx.showToast({
                title: res.msg || '验证失败',
                icon:'none',
                duration: 2000,
              })
           },0)
         }
       })
       
     },
     fail(res){
        wx.showToast({
            title: '验证失败',
            icon:'none',
            duration: 2000,
          })
        console.log(res)
     }
   })
 },
 toStaffManage() {
   wx.navigateTo({
     url: '/pages/staffManage/staffManage',
   })
 },
 toAfterSell() {
   wx.navigateTo({
     url: '/pages/afterSales/afterSales',
   })
 },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   //有切换门店功能，所有需要展示的数据请放到onshow
   const res = wx.getMenuButtonBoundingClientRect()
   this.setData({
    menuClientRect: res
   })
  },
loadYestData:function(){
  API_Stroe.getData().then(res=>{
    if(res.success){
      this.setData({
        totalPrice:res.totalPrice,
        totalSales:res.totalSales,
        visitNum:res.visitNum
      })
    }
  })
},
checkTips:function(){
  let that=this;
  API_Stroe.checkTips().then(res=>{
    if(res.code==200){
      let data=res.data;
      if(data.tips=='Y'){
        wx.showModal({
          confirmText:'去续费',
          cancelText:'关闭',
          title:'提示',
          content:data.tipsMsg,
          success (res) {
            if (res.confirm) {
             
             that.toVipPayment();
            }
          }
        })
      }
    }
  })
},
  goVerificationRecord(){
    wx.navigateTo({
      url: '/pages/verificationRecord/verificationRecord?type=2',
    })
  },

  //我的店铺
  toStoreInfo(){
    let store = JSON.stringify(this.data.store)
    wx.navigateTo({
      url: '../storeInfo/storeInfo?store='+store,
    })
  },

    //团单管理
  toProductList(){
    let that=this;
    if(!this.data.hasMember){
      wx.showToast({title:"请先进行实名及绑卡",duration:1500,icon:'none'});
      setTimeout(()=>{
          that.toShiMing();
      }, 1500)
   
      return;
    }
    if(!this.data.hasSettleAccount){
      wx.showToast({title:"请先绑定结算卡",duration:1500,icon:'none'});
      setTimeout(()=>{
          that.toBankCard();
      }, 1500)
      return;
    }
    wx.navigateTo({
      url: '../productList/productList',
    })
  },
   //财务管理
   toFinance(){
    let that=this;
    if(!this.data.hasMember){
      wx.showToast({title:"请先进行实名及绑卡",duration:1500,icon:'none'});
      setTimeout(()=>{
          that.toShiMing();
      }, 1500)
   
      return;
    }
    if(!this.data.hasSettleAccount){
      wx.showToast({title:"请先绑定结算卡",duration:1500,icon:'none'});
      setTimeout(()=>{
          that.toBankCard();
      }, 1500)
      return;
    }
    // wx.navigateTo({
    //   url: '../finance/finance',
    // })
    wx.navigateTo({
      url: '../finance2/finance',
    })
  },
  toShiMing(e){
    wx.navigateTo({
      url: '../shiming/shiming',
    })
   },
   toBankCard(e){
    wx.navigateTo({
      url: '../bankCard/bankCard',
    })
   },
    //评价管理
  toCommentList(){
      wx.navigateTo({
        url: '../commentList/commentList',
      })
  },
  goCoupons(){
    wx.navigateTo({
      url: '../couponsList/couponsList',
    })
  },
  //订单
  toOrderList(){
    wx.navigateTo({
      url: '../orderList/orderList',
    })
  },
    //技师
  toTeachingList(){
    wx.navigateTo({
      url: '../technicianList/technicianList',
    })
  },
  //会员
  toVipPayment(){
  wx.navigateTo({
    url: '../vipPayment/vipPayment',
  })
},
toJiShiMyInfo:function(){
    wx.navigateTo({
      url: '../technicianAdd/technicianAdd?jishiedit=Y',
    })
  },
  toJiShiOpus:function(){
    wx.navigateTo({
      url: '../technicianOpusList/technicianOpusList?jishiedit=Y',
    })
  },
  toFenXiaoHome:function(){
    wx.navigateTo({
      url: '../fenXiaoHome/fenXiaoHome',
    })
  },
  toAppointmentRecord:function(){
    wx.navigateTo({
      url: '../appointmentRecord/appointmentRecord',
    })
  },
  toAppointmentEdit:function(){
    wx.navigateTo({
      url: '../appointmentEdit/appointmentEdit',
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let store = wx.getStorageSync('store')
    this.setData({store:store})
    this.loadYestData();
    this.checkTips();
    getApp().watch(this.MY_MSG_UNREAD_COUNT,'MY_MSG_UNREAD_COUNT')//注册监听
    getApp().watch(this.RECEIVE_MSG_INFORM,'RECEIVE_MSG_INFORM')//注册监听
    let reqParam={storeId:this.data.store.id} ;
    socketUtil.sendData("MY_MSG_UNREAD_COUNT",reqParam);
    this.initshimingjiesuan();
    this.initMyStoreList();
    this.initShowView();
  },
  /**
   * 初始化哪些需要展示
   */
  initShowView(){
    let that=this;
    API_Stroe.getRoleTypes().then(res=>{
      let showStoreManager=false;
      let showYanQuan=false;
      let jishi=false;
      if(res.code==200){
        let list=res.data;
        if(list.indexOf('store_manager')>-1||list.indexOf('store_yunYing')>-1){
          showStoreManager=true;
          showYanQuan=true;
        }
        if(list.indexOf('store_jiShi')>-1){
          jishi=true;
        }
      }
      that.setData({
        showStoreManager:showStoreManager,
        showYanQuan:showYanQuan,
        jishi:jishi
      })
    })
  },
  initMyStoreList:function(){
    let that=this;
    API_Stroe.getMyStoreList().then(res=>{
      if(res.code==200){
        that.setData({storeList:res.data});
        that.checCanSee();
      }
    })
  },
  /**
   * 查看当前选的门店是否还有权限
   * */ 
  checCanSee:function(){
  let storeList=this.data.storeList;//所有有权限的
  let storeId = wx.getStorageSync('storeId');//选中的
  let hasRole=false;
  storeList.forEach(store => {
    console.info(store.id)
      if(store.id==storeId){
        //说明有权限
        hasRole=true;
      }
      
    });
    if(!hasRole){
      //没权限
      wx.reLaunch({
        url: '/pages/middlePage/middlePage',
      })
      wx.removeStorageSync('token')
      wx.removeStorageSync('member')
      wx.removeStorageSync('store')
      wx.removeStorageSync('loginType')
    }
  },
  /**
   * 初始化实名结算卡
   */
  initshimingjiesuan(){
    if(this.data.scanreturn){
      this.setData({scanreturn:false})
      return;
    }
    let that=this;
    API_Adamember.getMember().then(res=>{
        if(res.code==200){
        
          if(!res.data){
            that.setData({hasMember:false});
          }else{
            that.setData({hasMember:true});
          }
        }
    })
    API_Adamember.getSettleAccount().then(res=>{
        if(res.code==200){
          if(!res.data){
            that.setData({hasSettleAccount:false});
          }else{
            that.setData({hasSettleAccount:true});
          }
        }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

 
})